package com.dlkj.threadPool.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;


/**
 * @Author : lei
 * @Company ：DiLang Technology
 * @Date : 2019/1/11 15:37
 * @Description : 前后端数据传输加密工具类
 **/
public class AESEncryptUtil {

    // 配置Constant,16位,自定义
    private static String KEY = "123456789ABCDEFG";

    // 参数分别代表 算法名称/加密模式/数据填充方式
    private final static String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     * @param content 加密字符串
     * @param encryptKey key值
     * @return 加密结果
     */
    public static String encrypt(String content,String encryptKey) throws Exception {
        KeyGenerator kGen = KeyGenerator.getInstance("AES");
        kGen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(encryptKey.getBytes(),"AES"));
        byte[] bytes = cipher.doFinal(content.getBytes("UTF-8"));
        // 采用base64算法进行转码，避免出现中文乱码
        return Base64.encodeBase64String(bytes);
    }

    /**
     * 解密
     * @param encryptStr 需要解密字符串
     * @param decryptKey 加密的key
     * @return 解密后内容
     */
    public static String decrypt(String encryptStr,String decryptKey) throws Exception {
        KeyGenerator generator = KeyGenerator.getInstance("AES");
        generator.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(decryptKey.getBytes(),"AES"));
        // 采用base64算法转码，避免中文乱码
        byte[] encryptBytes = Base64.decodeBase64(encryptStr);
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String encrypt(String content) throws Exception {
        return encrypt(content, KEY);
    }

    public static String decrypt(String encryptStr) throws Exception {
        return decrypt(encryptStr,KEY);
    }
}
